/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年6月26日
 * @version 0.1
 */
package com.suredy.resource.ctrl;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.core.mvc.model.Tree;
import com.suredy.core.mvc.model.TreeMenu;
import com.suredy.resource.entity.MenuEntity;
import com.suredy.resource.entity.ResourceEntity;
import com.suredy.resource.model.Menu;
import com.suredy.resource.model.Resource;
import com.suredy.resource.model.ResourceType;
import com.suredy.resource.service.MenuSrv;
import com.suredy.resource.service.ResourceSrv;
import com.suredy.security.model.User;
import com.suredy.security.service.UserSrv;

/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "/config")
public class MenuCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(MenuCtrl.class);
	
	@Autowired
	private MenuSrv menuSrv;

	@Autowired 
	ResourceSrv resourceSrv;
	
	@Autowired
	private UserSrv userSrv;
	
	@RequestMapping({"menu/user"})
	@ResponseBody
	public Object UserMenuTree(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
		// not login
		if (user == null) {
			log.info("Session timeout or User didn't login.");
			return MessageModel.createErrorMessage("用户未登录或会话超时", null);
		}
		// 当前用户可访问的安全资源点
		List<String> userSecurityResources = this.userSrv.getPermissions(user.getUniqueCode());
		//TODO 读取数据库内的资源配置或者从Session读取，二选一
		//Set<String> permissions = this.userSrv.getPermissions(user.getUniqueCode());
		// 全部菜单相关的安全资源点
		List<Resource> menues = this.resourceSrv.getAll(ResourceType.Menu);
		// 已授权用户访问的菜单相关安全资源点
		Set<String> allowedMenues = new HashSet<String>();
		if(menues!=null)
		for (Resource menu : menues) {
			if (userSecurityResources.contains(menu.getUri())) {
				allowedMenues.add(menu.getId());
			}
		}

		List<TreeMenu> tree = this.menuSrv.getMenuTree(null, allowedMenues);
		if (tree == null || tree.isEmpty()) {
			return null;
		} 
		
		
		return tree;
	}
	
	
	
	@RequestMapping("menu/tree")
	@ResponseBody
	public Object ManagerMenuTree() {
		List<Tree> tree = this.menuSrv.getMenuTree(null);
		return tree == null ? null : tree;
	}
	
	@RequestMapping(value = "menu/manager")
	public ModelAndView MenuManager() {
		ModelAndView view = new ModelAndView("/config/resource/menu-manager");
		return view;
	}
	
	@RequestMapping(value = "menu/create")
	public ModelAndView MenuCreate() {
		ModelAndView view = new ModelAndView("/config/resource/menu-create");
		List<Resource> resources = this.resourceSrv.getAll(ResourceType.Menu);
		view.addObject("resources", resources);
		return view;
	}
	
	
	@RequestMapping("menu/create-save")
	@ResponseBody
	public Object MenuCreate(HttpServletRequest request) {
		String parentId = request.getParameter("parentId");
		String text = request.getParameter("text");
		String url = request.getParameter("url");
		String sort = request.getParameter("sort");
		String icon = request.getParameter("icon");
		String active = request.getParameter("active");
		String collapse = request.getParameter("collapse");
		
		if ( StringUtils.isBlank(text)) {
			log.info("Parameter String[text] is blank.");
			return MessageModel.createErrorMessage("参数不足, 菜单名称必须填写", null);
		}

		Date date = new Date();
		ResourceEntity resource = new ResourceEntity();
		resource.setCreateTime(date);
		resource.setLastModifiedTime(date);
		resource.setName(text);
		resource.setType(ResourceType.Menu.getType());
		resource.setUri(StringUtils.isBlank(url) ? null : url);
		
		
		MenuEntity menu = new MenuEntity();
		menu.setUrl(StringUtils.isBlank(url) ? null : url);
		menu.setText(text);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		menu.setIcon(StringUtils.isBlank(icon) ? null : icon);
		menu.setActive(Boolean.valueOf(active));
		menu.setCollapse(Boolean.valueOf(collapse));
		menu.setResource(resource);
		if (!StringUtils.isBlank(parentId)) {
			menu.setParent(new MenuEntity());
			menu.getParent().setId(parentId);
		}
		this.menuSrv.save(menu);
		
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "menu/edit")
	public ModelAndView MenuEdit(String menuId) {
		ModelAndView view = new ModelAndView("/config/resource/menu-edit");
		if (StringUtils.isBlank(menuId)) {
			log.info("Parameter String[menuId] is blank.");
			return view;
		}
		Menu menu = this.menuSrv.getById(menuId);
		Menu parent = null;
		if (menu.getParent() != null) {
			parent = this.menuSrv.getById(menu.getParent());
		} 
		
		List<Resource> resources = this.resourceSrv.getAll(ResourceType.Menu);
		view.addObject("resources", resources);
		view.addObject("menu", menu);
		if (parent != null) {
			view.addObject("parent", parent);
		}
		return view;
	}
	
	@RequestMapping("menu/edit-save")
	@ResponseBody
	public Object MenuEdit(HttpServletRequest request) {
		String id = request.getParameter("id");
		String parentId = request.getParameter("parentId");
		String text = request.getParameter("text");
		String url = request.getParameter("url");
		String sort = request.getParameter("sort");
		String icon = request.getParameter("icon");
		String active = request.getParameter("active");
		String collapse = request.getParameter("collapse");
		
		if (StringUtils.isBlank(id)) {
			return MessageModel.createErrorMessage("参数错误, 菜单ID不能为空", null);
		}
		
		MenuEntity menu = this.menuSrv.get(id);
		if (menu == null) {
			return MessageModel.createErrorMessage("参数错误, 未找到与ID对应的菜单信息", null);
		}
		if (StringUtils.isBlank(text)) {
			return MessageModel.createErrorMessage("参数不足, 菜单名称必须填写", null);
		}

		ResourceEntity resource = null;
		if ((resource = menu.getResource()) == null) {
			resource = new ResourceEntity();
			resource.setCreateTime(new Date());
			resource.setLastModifiedTime(new Date());
			resource.setName(text);
			resource.setType(ResourceType.Menu.getType());
			resource.setUri(StringUtils.isBlank(url) ? null : url);

			menu.setResource(resource);
		} else {
			resource.setName(text);
			resource.setUri(StringUtils.isBlank(url) ? resource.getId() : url);
		}
		
		menu.setUrl(StringUtils.isBlank(url) ? null : url);
		menu.setText(text);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		menu.setIcon(StringUtils.isBlank(icon) ? null : icon);
		menu.setActive(Boolean.valueOf(active));
		menu.setCollapse(Boolean.valueOf(collapse));

		if (!StringUtils.isBlank(parentId)) {
			if (! parentId.equals(id)) {
				menu.setParent(new MenuEntity());
				menu.getParent().setId(parentId);
			}
		} else {
			menu.setParent(null);
		}
		this.menuSrv.update(menu);

		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping("menu/delete")
	@ResponseBody
	public Object MenuDelete(String menuId) {
		if (StringUtils.isBlank(menuId)) {
			return MessageModel.createErrorMessage("无效的菜单ID！", null);
		}

		MenuEntity menu = this.menuSrv.get(menuId);

		if (menu == null) {
			return MessageModel.createErrorMessage("未找到与ID对应的菜单信息！", null);
		}

		try {
			this.menuSrv.delete(menu);
		} catch (Exception e) {
			return MessageModel.createErrorMessage("删除不成功,菜单信息映射错误！", null);
		}

		return MessageModel.createSuccessMessage(null, null);
	}
}
